package com.hnu.highlynewapp.service.impl;

import com.hnu.highlynewapp.exception.LoginFailException;
import com.hnu.highlynewapp.exception.RegisterFailException;
import com.hnu.highlynewapp.vo.RegisterVo;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnu.highlynewapp.utils.PageUtils;
import com.hnu.highlynewapp.utils.Query;

import com.hnu.highlynewapp.dao.UserDao;
import com.hnu.highlynewapp.entity.UserEntity;
import com.hnu.highlynewapp.service.UserService;
import org.springframework.util.DigestUtils;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(RegisterVo registerVo) throws RegisterFailException {
        if (registerVo.getPhone().length()!=11) {
            throw new RegisterFailException("请输入正确的电话号码");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone",registerVo.getPhone());
        UserEntity user = this.getOne(wrapper);
        if (user != null) {
            throw new RegisterFailException("此电话号已注册");
        }
        if (registerVo.getPassword().length()<6||registerVo.getPassword().length()>20) {
            throw new RegisterFailException("请输入6-20位密码");
        }
        if (!registerVo.getPassword().equals(registerVo.getConfirmedPassword())) {
            throw new RegisterFailException("密码和确认密码不匹配");
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setPhone(registerVo.getPhone());
        userEntity.setPassword(DigestUtils.md5DigestAsHex(registerVo.getPassword().getBytes()));
        userEntity.setGmtCreate(new Date());
        userEntity.setGmtModified(userEntity.getGmtCreate());
        //普通用户
        userEntity.setType(1);
        this.save(userEntity);
    }
}